// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2024-11-19

package file_plugin

import (
	"fmt"
	"gitee.com/go-libs/log/common"
	"gitee.com/go-libs/log/conf"
)

// 格式化工具.
type formatter struct{}

// +------------------------------------------------------------------------------+
// | Interface methods                                                            |
// +------------------------------------------------------------------------------+

func (o *formatter) ToByte(item common.Item) (body []byte) {
	if str := o.ToString(item); str != "" {
		body = []byte(str)
	}
	return
}

func (o *formatter) ToString(item common.Item) (str string) {
	cfg := conf.New()

	if cfg.FileAdapter.Json {
		return common.NewEntity(item).String()
	}

	// 1. 基础信息.
	str = fmt.Sprintf(`[%s][%s]`, item.Time().Format(cfg.TimeFormat.String()), item.Level())

	// 2. 链路信息.
	if s, sp := item.Span(); s != nil {
		if p, pp := item.ParentSpan(); p != nil {
			str += fmt.Sprintf("[%s-%s-%d-%s-%d]", item.TraceId(), p, pp, s, sp)
		} else {
			str += fmt.Sprintf("[%s-%s-%d]", item.TraceId(), s, sp)
		}
	}

	// 3. 日志正文.
	str += " " + item.Message()

	// 4. 堆栈信息.
	if item.Level().IsFatal() {
		if stack := item.Stack(); stack != nil {
			str += "\n" + stack.String()
		}
	}
	return
}

// +------------------------------------------------------------------------------+
// | Access methods                                                               |
// +------------------------------------------------------------------------------+

func (o *formatter) init() *formatter { return o }
